package org.raymond.iworks.study.netty.demo.echo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class LocalUDPDataReciever {
    private static final String TAG = LocalUDPDataReciever.class.getSimpleName();
    private static LocalUDPDataReciever instance = new LocalUDPDataReciever();
    private Thread thread = null;

    private LocalUDPDataReciever(){}

    public static LocalUDPDataReciever getInstance(){
        return instance;
    }

    public void startup(){
        Runnable runnable = ()->{
            // 开始监听
            try {
                LocalUDPDataReciever.this.udpListeningImpl();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        new Thread(runnable).start();
    }

    private void udpListeningImpl() throws Exception {
        while(true){
            byte[] data = new byte[1024];
            // 接收数据报的包
            DatagramPacket packet = new DatagramPacket(data, data.length);
            DatagramSocket localUdpSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket();
            if(localUdpSocket==null || localUdpSocket.isClosed()){
                continue;
            }

            // 阻塞直到收到数据
            localUdpSocket.receive(packet);
            // 解析服务端发过来的数据
            String receiveStr = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
        }
    }
}
